package com.freedom.start.common;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * controller增强类，处理相关异常
 *
 * @Author: zhenggang.liu
 * @Date: 2019/8/12 10:54
 */

@ControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    ShiroFilterFactoryBean shiroFilterFactoryBean;

    /**
     * 处理shiro的未授权异常
     *
     * @param e
     * @param model
     * @return
     */
    @ExceptionHandler({UnauthorizedException.class})
    public String unauthorizedExceptionHandler(UnauthorizedException e, Model model) {
        model.addAttribute("message", e.getMessage());
        return shiroFilterFactoryBean.getUnauthorizedUrl();
    }

    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Result bindExceptionHandler(BindException e) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getAllErrors();
        for (ObjectError error : allErrors) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                sb.append(fieldError.getField()).append("=[").append(fieldError.getRejectedValue()).append("]")
                        .append(fieldError.getDefaultMessage()).append(",");
            } else {
                sb.append(error.getDefaultMessage()).append(",");
            }
        }

        return Result.error(sb.toString());
    }

}
